package wangjg.mda.context;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import wangjg.mda.model.obj.Model;
import wangjg.mda.tra.ModelTrans;

/**
 * 
 * @author wangjg
 *
 */
public class FileSystemModelContext implements ModelContext {
	private Map<String,Long> modifiedMap = new HashMap<String,Long>();
	private Map<String,Model> modelMap = new HashMap<String,Model>();
	private List<String> dirList;
	private String charset;
	
	/**
	 * 先查缓存在调用loadModel加载
	 */
	public Model findModel(String name){
		File file = this.getFile(name);
		if(file==null){
			return null;
		}
		String key = name;
		Model model = modelMap.get(key);
		Long lastModified = modifiedMap.get(key);
		if(model==null||(lastModified!=null && lastModified<file.lastModified())){
			model = this.loadModel(file);
			this.modelMap.put(key, model);
			this.modifiedMap.put(key, file.lastModified());
		}
		return model;
	}
	
	public Model loadModel(File xmlFile){
		ModelTrans mt = new ModelTrans();
		Model model = new Model();//not Model
		mt.loadModel(model, xmlFile.getPath());
		return model;
	}
	
	protected File getFile(String name){
		if(dirList!=null){
			for(String dir : dirList){
				File file = new File(dir, name+".xml");
				if(file.exists()&&file.isFile()&&file.canRead()){
					return file;
				}
			}
		}
		return null;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public List<String> getDirList() {
		return dirList;
	}

	public void setDirList(List<String> dirList) {
		this.dirList = dirList;
	}
	
}
